package com.feng.service.impl;

import cn.hutool.core.io.IoUtil;
import com.feng.entity.RestResponse;
import com.feng.exception.SystemException;
import com.feng.service.UploadService;
import com.feng.utils.HttpCodeEnum;
import com.feng.utils.PathUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;

@Service
public class UploadServiceImpl implements UploadService {

    @Value("${upload.profile}")
    private String profile;

    @Value("${upload.path}")
    private String path;
    @Override
    public RestResponse upload(MultipartFile img) throws IOException {
        //判断文件类型
        if(!img.getOriginalFilename().endsWith(".jpg") && !img.getOriginalFilename().endsWith(".png")){
            throw new SystemException(HttpCodeEnum.FILE_TYPE_ERROR);
        }
        String imgPath = PathUtils.imgPath(path,img.getOriginalFilename());

        long copySize = IoUtil.copy(img.getInputStream(),
                new FileOutputStream(path + "/"+ imgPath),
                IoUtil.DEFAULT_BUFFER_SIZE);
        if(!(copySize > 0)) return RestResponse.failure(400,"文件上传失败");
//        return RestResponse.success("/src/assets/upload/" + imgPath);
        return RestResponse.success(profile + "/" + imgPath);
    }
}
